﻿using Microsoft.Extensions.DependencyInjection;
using System.Text;
using System.Windows;
using System.Windows.Threading;
using Om.Core.Extension;
using Om.Core.Singleton;
using OptoMeasure.Views;

namespace OptoMeasure
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// 获取当前 App 实例
        /// </summary>
        public new static App Current => (App)Application.Current;
        /// <summary>
        /// 获取存放应用服务的容器
        /// </summary>
        public IServiceProvider ServiceProvider { get; }

        public App()
        {
            ServiceProvider = ConfigureServices();
            InitializeComponent();
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            //此方法在启动时调用，获取容器中的MainWindow实例并显示。
            //在外部获取所需服务时可调用App.Current.ServiceProvider.GetRequiredService<T>()方法 。
            //var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
            //mainWindow.Show();

            DevicesConfig.Instance.LoadConfig();
            await CmdAirClient.Instance.Connect(DevicesConfig.Instance.AirClientCom);
            CameraUdpManager.Instance.Start();

            //UI线程未捕获异常处理事件
            this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            //Task线程内未捕获异常处理事件
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            //非UI线程未捕获异常处理事件
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        protected override void OnExit(ExitEventArgs e)
        {
            DevicesConfig.Instance.SaveConfig();
            base.OnExit(e);
        }

        /// <summary>
        /// 配置应用的服务
        /// </summary>
        private static IServiceProvider ConfigureServices()
        {
            var service = new ServiceCollection();

            service.AddSingleton<MainViewModel>();

            service.AddSingleton<DevicesConnectView>();
            service.AddSingleton<DevicesConnectViewModel>();


            return service.BuildServiceProvider();
        }



        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                e.Handled = true; //把 Handled 属性设为true，表示此异常已处理，程序可以继续运行，不会强制退出      
                //MessageBox.Show("UI线程异常:" + e.Exception.Message);
            }
            catch (Exception ex)
            {
                //此时程序出现严重异常，将强制结束退出
                //MessageBox.Show("UI线程发生致命错误！");
            }

        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            StringBuilder sbEx = new StringBuilder();
            if (e.IsTerminating)
            {
                sbEx.Append("非UI线程发生致命错误");
            }
            sbEx.Append("非UI线程异常：");
            if (e.ExceptionObject is Exception)
            {
                sbEx.Append(((Exception)e.ExceptionObject).Message);
            }
            else
            {
                sbEx.Append(e.ExceptionObject);
            }
            //MessageBox.Show(sbEx.ToString());
        }

        void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            //task线程内未处理捕获
            // MessageBox.Show("Task线程异常：" + e.Exception.Message);
            LogHelper.Log("Task线程异常：" + e.Exception.Message);
            e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
        }
    }



}


